<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    正在测试ajax的get封装
    <input type="button" value="按钮1" id="btn1">
    <input type="button" value="按钮2" id="btn2">
    <input type="button" value="按钮3" id="btn3">
    <div id="box"></div>
</body>
<!-- <script src="../ajax.js"></script> -->
<script>

    const obtn1 = document.getElementById("btn1")
    const obtn2 = document.getElementById("btn2")
    const obtn3 = document.getElementById("btn3")

    obtn1.onclick = function(){
        ajaxGet("http://localhost:3000/api", function(res){
            document.getElementById("box").innerHTML = res;
        },{
            a:10,
            b:20
        });
    }
    obtn2.onclick = function(){
        ajaxGet("http://localhost:3000/api", function(res){
            console.log(res);
        },{
            abc:"hello"
        });
    }
    obtn3.onclick = function(){
        ajaxGet("http://localhost:3000/api", function(res){
            alert(res);
        },{
            qwe:"hahahah",
            zxc:"world"
        });
    }

    function ajaxGet(url, callback, obj){
        // 1. 处理数据：名字=值&名字=值
        let str = "";
        for(let i in obj){
            str += `${i}=${obj[i]}&`;
        }
        // console.log(str.slice(0,str.length-1));

        // 2. 处理url
        url += "?" + str.slice(0,str.length-1)
        // console.log(url);

        // 3. 开启ajax
        const xhr = new XMLHttpRequest();
        xhr.open("get",url);
        xhr.send();
        xhr.onload = function(){
            if(xhr.status === 200){ 
                // 4. 执行成功的处理函数
                callback(xhr.responseText);
            }
        }
    }

</script>
</html>